//
//  AdScrollView.m
//  ZCStudyDemo
//
//  Created by XFB on 2018/9/11.
//  Copyright © 2018年 ZhouCheng. All rights reserved.
//

#import "AdScrollView.h"
#import "AdCollectionViewCell.h"
#import "SYPageControl.h"

static NSInteger const adHorizonScrollViewMaxSections = 100;

@interface AdScrollView () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) SYPageControl *pageControl;

@end


@implementation AdScrollView

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setupSubviews];
    [self initialization];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        [self setupSubviews];
        [self initialization];
    }
    return self;
}

- (void)initialization
{
    /// 滚动时间间隔，默认为3s
    _scrollTimeInterval = 3;
    /// 添加定时器
    [self addTimer];
}

- (void)addTimer
{
    [self removeTimer];
    self.timer = [NSTimer timerWithTimeInterval:self.scrollTimeInterval target:self selector:@selector(beginUpdateUI) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

/// 移除定时器
- (void)removeTimer
{
    [_timer invalidate];
    _timer = nil;
}

- (void)beginUpdateUI
{
    if (self.modelArray.count == 0) return;
 
    /// 1.当前正在展示的位置
    NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
    /// 马上显示回最中间那组数据
    NSIndexPath *resetCurrentIndexPath = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:adHorizonScrollViewMaxSections/2];
    [self.collectionView scrollToItemAtIndexPath:resetCurrentIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];

    /// 2、计算出下一个需要展示的位置
    NSInteger nextItem = resetCurrentIndexPath.item + 1;
    NSInteger nextSection = resetCurrentIndexPath.section;
    
    if (nextItem == self.modelArray.count) {
        nextItem = 0;
        nextSection ++;
    }
    
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
    /// 3.通过动画滚动到下一个位置
    [self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}

- (void)setupSubviews
{
    [self addSubview:self.collectionView];
    
    self.pageControl = [[SYPageControl alloc] initWithFrame:CGRectMake(0, 0, 60, 40)];
    self.pageControl.backgroundColor = [UIColor whiteColor];
    self.pageControl.center = CGPointMake((self.frame.size.width)*0.5, 80);
    self.pageControl.pageIndicatorColor = [UIColor lightGrayColor];
    self.pageControl.currentPageIndicatorColor = [UIColor blueColor];
    self.pageControl.currentPage = 0;
    self.pageControl.pageMargin = 0.0;
    self.pageControl.pageSizeWidth = 15;
    self.pageControl.pageSizeHeight = 3;
    [self addSubview:self.pageControl];
}

- (UICollectionView *)collectionView
{
    if (_collectionView == nil) {
        
        _flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _flowLayout.minimumLineSpacing = 0;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 60) collectionViewLayout:_flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.scrollsToTop = NO;
        _collectionView.scrollEnabled = NO;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = YES;
        _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        /// 自定义collectionView
        
        [_collectionView registerNib:[UINib nibWithNibName:@"AdCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"collectionView"];
    }
    return _collectionView;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    _flowLayout.itemSize = CGSizeMake(self.frame.size.width, 60);
    _collectionView.frame = CGRectMake(0, 0, self.frame.size.width, 60);

    self.pageControl.numberOfPages = self.modelArray.count;

    
    if (self.modelArray.count > 1) {
        [self defaultSelectedSection];
    }
}

- (void)defaultSelectedSection
{
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:adHorizonScrollViewMaxSections/2] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}

#pragma mark --- <UICollectionViewDataSource、UICOllectionViewDelegate>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return adHorizonScrollViewMaxSections;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.modelArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    AdCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionView" forIndexPath:indexPath];
    NSInteger redValue = arc4random() % 255;
    NSInteger greenValue = arc4random() % 255;
    NSInteger blueValue = arc4random() % 255;
    UIColor *randColor = [UIColor colorWithRed:redValue / 255.0f green:greenValue / 255.0f blue:blueValue / 255.0f alpha:1.0f];
    cell.backgroundColor = [UIColor whiteColor];
    cell.replyDict = self.modelArray[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%ld", indexPath.item);
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    /// 移除定时器
    [self removeTimer];
}

/// 滚动减速停止的时候
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self addTimer];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int page = (int) (scrollView.contentOffset.x/scrollView.frame.size.width+0.5)%self.modelArray.count;
    
    self.pageControl.currentPage = page;

//    [UIView animateWithDuration:0.5 animations:^{
//        self.pageControl.currentPage = page;
//    }];
}

@end
